const app = getApp();

Page({
  data: {
    favorites: [],
    currentSong: null,
    isPlaying: false
  },

  onLoad() {
    this.loadFavorites();
  },

  onShow() {
    this.updatePlaybackStatus();
  },

  loadFavorites() {
    const favorites = app.getFavorites();
    this.setData({
      favorites: favorites
    });
  },

  updatePlaybackStatus() {
    const { currentSong, isPlaying } = app.globalData;
    this.setData({
      currentSong,
      isPlaying
    });
  },

  playSong(e) {
    const song = e.currentTarget.dataset.song;
    if (song) {
      app.playSong(song);
      app.addToHistory(song);
      
      this.setData({
        currentSong: song,
        isPlaying: true
      });
    }
  },

  removeFavorite(e) {
    const song = e.currentTarget.dataset.song;
    if (song) {
      const success = app.removeFromFavorites(song);
      if (success) {
        this.loadFavorites();
        wx.showToast({
          title: '已取消收藏',
          icon: 'success'
        });
      }
    }
  },

  clearAllFavorites() {
    if (this.data.favorites.length === 0) return;
    
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有收藏吗？',
      success: (res) => {
        if (res.confirm) {
          try {
            wx.setStorageSync('music_favorites', []);
            this.setData({
              favorites: []
            });
            wx.showToast({
              title: '收藏已清空',
              icon: 'success'
            });
          } catch (error) {
            wx.showToast({
              title: '清空失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  onShareAppMessage() {
    return {
      title: '我的音乐收藏',
      path: '/pages/favorites/favorites'
    };
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  },

  // 时间格式化函数
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const now = Date.now();
    const diff = now - timestamp;
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    
    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else if (diff < 7 * day) {
      return Math.floor(diff / day) + '天前';
    } else {
      const date = new Date(timestamp);
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  }
});